package org.domain.sigepac.validator;

import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.ValueHolder;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

@Name("PeriodoValidator")
@org.jboss.seam.annotations.faces.Validator
@BypassInterceptors
public class PeriodoValidator implements Validator {

  public static UIComponent findComponent(FacesContext context,
      UIComponent parent, String id) {
    if (parent == null) {
      parent = context.getViewRoot();
      if (parent == null) {
        return null;
      }
    }

    if (parent.getId() != null && parent.getId().equals(id)) {
      return parent;
    } else {
      for (UIComponent comp : parent.getChildren()) {
        UIComponent found = findComponent(context, comp, id);

        if (found != null) {
          return found;
        }
      }
    }

    return null;
  }

  public void validate(FacesContext ctx, UIComponent comp, Object value)
      throws ValidatorException {
    Date fim = (Date) value;

    if (fim == null) {
      return;
    }

    String dataInicioId = (String) comp.getAttributes().get("dataInicio");
    if (dataInicioId == null) {
      throw new ValidatorException(new FacesMessage(
          "Favor passar o atributo dataInicio"));
    }

    UIComponent dtInicio = findComponent(ctx, comp.getParent(), dataInicioId);
    if (dtInicio == null) {
      throw new ValidatorException(
          new FacesMessage(
              "Componente identificado pelo atributo dataInicio n\u00e3o foi encontrado"));
    }

    Date inicio = (Date) ((ValueHolder) dtInicio).getValue();

    if (inicio == null) {
      return;
    }

    if (fim.before(inicio)) {
      throw new ValidatorException(new FacesMessage(
          FacesMessage.SEVERITY_ERROR, "Data final menor que a inicial",
          "A data final dever\u00e1 ser maior que a inicial, favor corrigir."));
    }
  }
}
